<!--
 * @Author: your name
 * @Date: 2020-12-17 19:14:17
 * @LastEditTime: 2021-08-08 11:30:24
 * @LastEditors: Please set LastEditors
 * @Description: 备货通知根据原单生成功能,返回的数据 为
 * @FilePath: \cang-chu-guan-li-xi-tong\src\views\chukuguanli\BeiHuoTongZhiOrderOrigin.vue
-->
<template>
  <div>
    <a-button type="primary" style="margin-top: 20px" @click="showModal">
      <a-icon type="plus" />
      根据源单生成
    </a-button>

    <a-modal
      title="销售订单生成销售出库单"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      width="70%"
    >
      <!-- 搜索表单---查询条件 -->
      <a-form v-bind="layout">
        <a-row>
          <!-- 销售订单显示 -->
          <!-- <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-item label="销售部门">
              <a-select
                showSearch
                style="width: 100%"
                @change="DepartmentChange"
                v-model="searchForm.salesDepartment"
              >
                <a-select-option
                  v-for="item in saleDepartmentList"
                  :key="item.value"
                  :value="item.title"
                  >{{ item.title }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col> -->
          <!-- 公共部分 -->
          <a-col :xl="10" :lg="10" :md="12" :sm="24" :xs="24">
            <a-form-item label="时间段">
              <a-range-picker
                v-model="searchForm.rangeDate"
                @change="getRangeTime"
              />
            </a-form-item>
          </a-col>

          <a-col :xl="10" :lg="10" :md="12" :sm="24" :xs="24">
            <a-form-item label="单据状态">
              <a-select
                v-model="searchForm.documentClosed"
                @change="changeOrderStatus"
                style="width: 100%"
              >
                <a-select-option
                  v-for="item in documentClosedList"
                  :key="item"
                  :value="item"
                >
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :xl="10" :lg="10" :md="12" :sm="24" :xs="24">
            <a-form-item label="订单单号">
              <a-input
                v-model="searchForm.documentNo"
                style="width: 100%"
                placeholder="订单编号"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="10" :lg="10" :md="12" :sm="24" :xs="24">
            <a-form-item label="业务员">
              <a-select
                v-model="searchForm.salesman"
                style="width: 100%"
                placeholder="请选择业务员"
                @change="changeSalesMan"
                showSearch
                @search="searchUserInfoList"
              >
                <a-select-option
                  v-for="item in salesManList"
                  :key="item.userId"
                  :value="item.userName"
                >
                  {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="10" :lg="10" :md="12" :sm="24" :xs="24">
            <a-form-item label="客户">
              <a-select
                v-model="searchForm.clientName"
                style="width: 100%"
                placeholder="请选择客户名称"
                @search="searchCustomer"
                showSearch
                @change="changeCustomer"
              >
                <a-select-option
                  v-for="item in clientIdList"
                  :key="item.id"
                  :value="item.customerCode + '|' + item.name + '|' + item.id"
                >
                  {{ item.name }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="10" :lg="10" :md="8" :sm="24" :xs="24">
            <a-form-model-item ref="" label="发货仓库" prop="">
              <a-select
                placeholder=""
                v-model="searchForm.shippingWarehouse"
                @change="setShippingWarehouse"
                showSearch
              >
                <a-select-option
                  v-for="item in shippingWarehouseList"
                  :key="item.depotId"
                  :value="item.depotNo + '|' + item.depotName"
                  >{{ item.depotNo }}{{ item.depotName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :xl="10" :lg="10" :md="12" :sm="24" :xs="24"></a-col>
          <!-- 按钮 -->
          <a-col
            :xl="4"
            :lg="4"
            :md="24"
            :sm="24"
            :xs="24"
            :style="{ textAlign: 'right' }"
            ><div style="margin-top: 10px">
              <a-button type="primary" @click="Search()">查询</a-button>
              <a-button style="margin-left: 8px" @click="Reset()"
                >重置</a-button
              >
            </div>
          </a-col>
        </a-row>
        <a-row> </a-row>
      </a-form>

      <a-divider />

      <!-- 备货通知单、销售订单等单据 -->
      <a-table
        style="margin-top: 20px"
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        @change="handleTableChange"
        :row-selection="{
          selectedRowKeys: orderSelectedRowKeys,
          onChange: orderSelectChange,
          type: 'radio',
        }"
        :scroll="{ x: 1300 }"
      >
        <template slot="options" slot-scope="text, record">
          <a-popconfirm
            ok-text="确定"
            cancel-text="取消"
            @confirm="closeOrder(record.id, record.documentClosed)"
          >
            <template slot="title">
              <p v-if="record.documentClosed == '关闭'">是否开启单据？</p>
              <p v-if="record.documentClosed != '关闭'">是否关闭单据？</p>
            </template>
            <a type="danger"> {{ record.documentClosed }} </a>
          </a-popconfirm>
        </template>
      </a-table>

      <a-divider />
      <!-- 单据中的物品 -->
      <a-table
        style="margin-top: 10px"
        :pagination="false"
        :columns="listColumns"
        :data-source="listDataSource"
        :scroll="{ x: 1500 }"
        :row-selection="{
          selectedRowKeys: listSelectedRowKeys,
          onChange: listSelectChange,
        }"
      >
        <template slot="options" slot-scope="text, record">
          <a-popconfirm
            ok-text="确定"
            cancel-text="取消"
            @confirm="closeGoods(record.id, record.documentClosed)"
          >
            <template slot="title">
              <p>是否确定？</p>
            </template>
            <a type="danger"> {{ record.documentClosed }} </a>
          </a-popconfirm>
        </template>
      </a-table>

      <!-- 备货通知单物品信息   -->
    </a-modal>
  </div>
</template>

<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口

const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
    width: "80px",
  },
  {
    title: "订单单号",
    dataIndex: "documentNo",
    key: "documentNo",
    align: "center",
  },
  {
    title: "发货仓库",
    dataIndex: "cwarehouseid_dictText",
    key: "cwarehouseid_dictText",
    align: "center",
  },
  {
    title: "销售组织",
    dataIndex: "csalecorpid_dictText",
    key: "csalecorpid_dictText",
    align: "center",
  },
  {
    title: "业务员",
    dataIndex: "salesMan_dictText",
    key: "salesMan_dictText",
    align: "center",
  },
  {
    title: "客户",
    dataIndex: "clientId_dictText",
    key: "clientId_dictText",
    align: "center",
  },
  {
    title: "币种",
    dataIndex: "currency",
    key: "currency",
    align: "center",
  },
  {
    title: "是否赠品",
    dataIndex: "giveaway_dictText",
    key: "giveaway_dictText",
    align: "center",
  },
  {
    title: "订单日期",
    dataIndex: "documentDate",
    key: "documentDate",
    align: "center",
  },
  {
    title: "业务流程",
    dataIndex: "cbiztype_dictText",
    key: "cbiztype_dictText",
    align: "center",
  },
  {
    title: "库存组织",
    dataIndex: "ccalbodyid_dictText",
    key: "ccalbodyid_dictText",
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "options",
    key: "options",
    align: "center",
    scopedSlots: { customRender: "options" },
  },
];

const listColumns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
    width: "80px",
  },
  {
    title: "存货编码",
    dataIndex: "inventoryNo",
    key: "inventoryNo",
    align: "center",
  },
  {
    title: "存货名称",
    dataIndex: "inventoryName",
    key: "inventoryName",
    align: "center",
  },
  {
    title: "规格型号",
    dataIndex: "specifications",
    key: "specifications",
    align: "center",
  },
  {
    title: "单位",
    dataIndex: "unit",
    key: "unit",
    align: "center",
  },
  {
    title: "辅助单位",
    dataIndex: "unitMeasurement",
    key: "unitMeasurement",
    align: "center",
  },
  {
    title: "数量",
    dataIndex: "quantity",
    key: "quantity",
    align: "center",
  },

  // {
  //   title: "单价原币",
  //   dataIndex: "unitPriceOriginalCurrency",
  //   key: "unitPriceOriginalCurrency",
  //   align: "center",
  // },
  // {
  //   title: "金额原币",
  //   dataIndex: "amountOfOriginalCurrency",
  //   key: "amountOfOriginalCurrency",
  //   align: "center",
  // },

  {
    title: "单价",
    dataIndex: "unitPrice",
    key: "unitPrice",
    align: "center",
  },
  {
    title: "金额",
    dataIndex: "money",
    key: "money",
    align: "center",
  },
  {
    title: "交货日期",
    dataIndex: "deliveryDate",
    key: "deliveryDate",
    align: "center",
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "options",
    key: "options",
    align: "center",
    scopedSlots: { customRender: "options" },
  },
];

export default {
  data() {
    return {
      visible: false,
      searchForm: {
        salesDepartment: "", // 销售部门
        deptId: "", // 销售部门Id
        rangeDate: null, // 日期范围
        startTime: "", // 开始日期
        endTime: "", // 结束日期
        documentClosed: "开启",
        clientCode: null,
        clientName: null,
        shippingWarehouse: null, //发货仓库
        shippingWarehouseNo: "", //发货仓库
        shippingWarehouseId: "", //发货仓库Id
      },
      saleDepartmentList: [], // 销售部门
      documentClosedList: ["开启", "关闭"],
      ClientList: [], // 客户列表

      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 15 },
      },

      columns,
      dataSource: [],
      orderSelectedRowKeys: [],

      listColumns,
      listDataSource: [],
      listSelectedRowKeys: [], // 列表选择

      pagination: {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        showSizeChanger: true,
        // pageSizeOptions: ["5"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
        pageSizeOptions: ["5", "10", "20"], //每页中显示的数据
      },
      queryParam: {
        //查询参数
        page: 1, //第几页
        size: 10, //每页中显示数据的条数
        hosName: "",
        hosCode: "",
        province: "",
        city: "",
      },
      SelectData: [], // 选中的值

      goodsList: [], // 物品列表
      documentNoList: [], //销售订单号

      clientIdList: [], //客户名称列表
      salesManList: [], // 业务员列表

      Form: {
        requisitionNo: "", // 订单号
        ccalbodyid: "", //库存组织id
        ccalbodyid_dictText: "", //库存组织
        applicationDept: "", // 申请销售部门
        applicationDeptId: "", // 申请销售部门Id
        clientId: "", // 客户
        client: "", // 客户名称
        giveaway: "", // 是否赠品
        giveawayId: "", // 是否赠品
        goodsList: [], // 物品列表
      },
      shippingWarehouseList: [], // 发货仓库列表
    };
  },
  mounted() {
    this.getSaleDepartmentList();
    this.getSaleOrderList();
    this.getOrderList();
    this.getclientIdInfo();
    this.searchUserInfoList();
    this.getWarehouseInfo();
  },
  methods: {
    // 申请仓库列表
    getWarehouseInfo() {
      comHttp.getStorageName("?pageSize = 10000").then((res) => {
        console.log("申请仓库列表", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            depotId: res.result[i].pkStordoc,
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
          };
          this.shippingWarehouseList.push(data);
        }
      });
    },
    // 选择申请仓库后设置表格中的申请仓库，并渲染该仓库下拥有的物品
    setShippingWarehouse(value, option) {
      console.log(value);
      console.log("option!!!!!!", option);
      let array = [];
      array = value.split("|");
      this.searchForm.shippingWarehouse = array[1];
      this.searchForm.shippingWarehouseNo = array[0];
      this.searchForm.shippingWarehouseId = option.key;
    },
    // 业务员模糊查询
    searchUserInfoList(value) {
      this.salesManList = [];
      // this.workNoList = [];
      if (value != "") {
        let queryPath = "?username=" + value;
        comHttp.getUserInfoByUserName(queryPath).then((res) => {
          console.log("mohgljfdsjlkfdjdslk", res);
          for (let i = 0; i < res.result.list.length; i++) {
            let data = {
              userName: res.result.list[i].username,
              userId: res.result.list[i].id,
              workNo: res.result.list[i].workNo,
            };
            this.salesManList.push(data);
          }
        });
      }
    },

    //! 业务员的处理函数
    changeSalesMan(value, option) {
      this.searchForm.salesman = value;
      this.searchForm.salesmanId = option.key;
      let sum = 0;
      for (let i = 0; i < this.dataSource.length; i++) {
        sum = Number(sum) + Number(this.dataSource[i].amount);
      }
      this.searchForm.jinezongheji = sum;
      console.log(this.searchForm.jinezongheji, 3333333333333);
    },

    // !客户名称处理函数
    changeCustomer(value) {
      console.log("value111111111111111111", value);
      let array = value.split("|");
      this.searchForm.clientCode = array[0]; //客户编码
      this.searchForm.clientName = array[1]; //客户名称
      this.searchForm.clientId = array[2]; //客户Id
    },

    // 获取供应商信息的列表
    getclientIdInfo() {
      let pageNo = 1;
      comHttp.getCustomerNameInfo("?pageNo=" + pageNo).then((res) => {
        console.log(res);
        for (let i = 0; i < res.result.records.length; i++) {
          let data = {
            id: res.result.records[i].id,
            name: res.result.records[i].name,
          };
          this.clientIdList.push(data);
        }
      });
    },

    // !客户名称搜索函数
    searchCustomer(value) {
      this.clientIdList = [];
      if (value == "") {
        this.$message.error("请输入客户名称！");
      } else if (value == " ") {
        value = "";
        console.log("value", value);
        this.$message.error("请输入真实数据！");
      } else {
        console.log("value", value);

        let data = "?customerName=" + value + "&custflag=2,0";
        console.log("data!!!!!!!!", data);
        comHttp.getCustomerInfoByName(data).then((res) => {
          console.log("res111111111111111", res);
          for (let i = 0; i < res.result.list.length; i++) {
            let data = {
              id: res.result.list[i].pkCumandoc,
              customer_code: res.result.list[i].custcode,
              name: res.result.list[i].custname,
            };
            this.clientIdList.push(data);
          }
          console.log("getCustomerInfoByName", this.clientIdList);
        });
      }
    },

    // ----------- 获取销售订单列表 --------------
    getSaleOrderList(
      queryPath = "?pageNo=1&pageSize=5&status=审核通过&documentClosed=开启"
    ) {
      comHttp.getSaleOrderList(queryPath).then((res) => {
        console.log("获取销售订单", res);
        this.dataSource = [];
        const pagination = { ...this.pagination };
        pagination.total = res.result.total;
        pagination.pageSize = res.result.size;
        this.pagination = pagination;

        this.dataSource = res.result.records;
        for (let i = 0; i < this.dataSource.length; i++) {
          this.dataSource[i].key = (res.result.current - 1) * 5 + i + 1;
        }
      });
    },
    // ——————————————获取销售订单单据号——————
    getOrderList() {},
    // ----------- 获取销售部门列表 --------------
    getSaleDepartmentList() {
      this.saleDepartmentList = [];
      comHttp.getSaleDepartment().then((res) => {
        console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: res.result[i].value,
            title: res.result[i].title,
          };
          this.saleDepartmentList.push(data);
        }
      });
    },

    // 部门按钮触发
    DepartmentChange(value, options) {
      this.searchForm.deptId = options.key;
    },

    // 时间段
    getRangeTime(date, dateString) {
      this.searchForm.startTime = dateString[0];
      this.searchForm.endTime = dateString[1];
    },

    // 列表选择
    listSelectChange(selectedRowKeys, selectedRows) {
      this.listSelectedRowKeys = selectedRowKeys;
      console.log(selectedRows);
      this.Form.goodsList = selectedRows;
    },

    // 物品选择
    orderSelectChange(selectedRowKeys, selectedRows) {
      this.orderSelectedRowKeys = selectedRowKeys;
      this.listSelectedRowKeys = [];
      this.Form = selectedRows[0];
      this.Form[`goodsList`] = [];
      this.getSaleGoodsById(selectedRows[0].id);
    },

    // 通过销售订单单号ID,查询物品信息
    getSaleGoodsById(id) {
      comHttp.getSaleGoodsByOrderId("?otherId=" + id).then((res) => {
        this.listDataSource = res.result.list;
        this.Form.goodsList = res.result.list;
        for (let i = 0; i < this.Form.goodsList.length; i++) {
          this.Form.goodsList[i].key = i + 1;
        }
      });
    },

    // ----------- 重置 ------------------
    // 对话框取消
    handleCancel() {
      this.Reset();
      this.visible = false;
    },
    // 重置
    Reset() {
      this.searchForm = {
        documentClosed: "开启",
        salesDepartment: "", // 销售部门
        deptId: "", // 销售部门Id
        rangeDate: null, // 日期范围
        startTime: "", // 开始日期
        endTime: "", // 结束日期
        clientCode: null,
        clientName: null,
        clientId: null,
        shippingWarehouse: null, //发货仓库
        shippingWarehouseNo: "", //发货仓库
        shippingWarehouseId: "", //发货仓库Id
      }; // 重置查询条件

      this.resetPagination(); // 重置分页情况
      this.getSaleOrderList(); // 重置销售订单
      this.listDataSource = []; // 重置物品数据
      this.listSelectedRowKeys = []; // 重置选择框中选中的值
      this.orderSelectedRowKeys = [];
    },

    // 重置当前页码及页码参数
    resetPagination() {
      this.pagination = {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ["5"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      };
      //查询参数
      this.queryParam = {
        page: 1, //第几页
        size: 10, //每页中显示数据的条数
        hosName: "",
        hosCode: "",
        province: "",
        city: "",
      };
    },

    // ----------- 查询 ------------------
    // 查询
    Search() {
      let queryPath = this.getQueryPath();
      this.getSaleOrderList(queryPath);
      console.log("查询条件为:::", queryPath);
    },
    // 分页函数
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.queryParam.page = pagination.current;
      this.queryParam.size = pagination.pageSize;
      let queryPath = this.getQueryPath();
      this.getSaleOrderList(queryPath);
    },

    // 获取全局查询条件
    getQueryPath() {
      console.log(this.searchForm);
      let queryPath =
        "?pageNo=" +
        this.queryParam.page +
        "&pageSize=" +
        this.queryParam.size +
        "&beginDate=" +
        this.searchForm.startTime +
        "&endDate=" +
        this.searchForm.endTime +
        "&documentClosed=" +
        this.searchForm.documentClosed +
        "&status=审核通过";
      // 订单编号
      queryPath += this.searchForm.documentNo
        ? `&documentNo=${this.searchForm.documentNo}`
        : "";

      // 客户
      queryPath += this.searchForm.clientId
        ? `&clientId=${this.searchForm.clientId}`
        : "";

      queryPath += this.searchForm.salesmanId
        ? `&salesMan=${this.searchForm.salesmanId}`
        : "";
      queryPath += this.searchForm.shippingWarehouseId
        ? `&cwarehouseid=${this.searchForm.shippingWarehouseId}`
        : "";

      return queryPath; // 返回的查询条件
    },

    // 打开对话框
    showModal() {
      this.visible = true;
    },
    // 对话框提交
    handleOk() {
      this.$emit("select-data", this.Form);
      this.visible = false;
    },

    // 关闭订单
    closeOrder(id, documentClosed) {
      let data = {
        id: id,
      };
      if (documentClosed == "开启") {
        data.documentClosed = "关闭";
      } else {
        data.documentClosed = "开启";
      }

      comHttp.changeSaleOrderInfo(data).then((res) => {
        if (res.success) {
          this.getSaleOrderList();
        }
      });
    },
    // 关闭物品
    closeGoods(id, documentClosed) {
      let data = {
        id: id,
      };
      if (documentClosed == "开启") {
        data.documentClosed = "关闭";
      } else {
        data.documentClosed = "开启";
      }

      comHttp.changeSaleGoodsInfo(data).then((res) => {
        if (res.success) {
          this.getSaleGoodsById(this.Form.id);
        }
      });
    },
    // 改变单据状态
    changeOrderStatus() {
      this.Search();
    },
    changedocumentNo() {
      this.Search();
    },
  },
};
</script>

<style></style>
